package cn.lx.es.query.registrar;

import cn.lx.es.query.annotation.EnableDynamicEsQuery;
import cn.lx.es.query.processor.SearchAnnotationProcessor;
import cn.lx.es.query.scanner.ESEntityScanner;
import cn.lx.es.query.scanner.ESProcessorScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SearchProcessorRegistrar
 * @Description: 搜索处理器自动注册器
 * @Author: 落雪
 * @CreateDate: 2025/7/3 10:30
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/7/3 10:30
 * @UpdateRemark:
 * @Version: 1.0
 */
public class SearchProcessorRegistrar implements ImportBeanDefinitionRegistrar, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private static final String PROCESSOR_BASE_PACKAGE = "cn.lx.es.query.processor";

    // 内置处理器类列表


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attrs = importingClassMetadata.getAnnotationAttributes(EnableDynamicEsQuery.class.getName());
        String[] basePackages = (String[]) attrs.get("processorBasePackages");

        // 1. 扫描指定包下所有带@EsIndex注解的类
        if(basePackages == null || basePackages.length == 0){
            basePackages = new String[]{PROCESSOR_BASE_PACKAGE};
        }else {
            basePackages = Arrays.copyOf(basePackages, basePackages.length + 1);
            basePackages[basePackages.length - 1] = PROCESSOR_BASE_PACKAGE;
        }

        ESProcessorScanner scanner = new ESProcessorScanner( registry);
        scanner.setResourceLoader( this.applicationContext);
        scanner.scan(basePackages); // 需实现
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                this.applicationContext = applicationContext;
    }
}
